package cc.loach.homekit.app;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

import cc.loach.homekit.app.homekit.HomeKit;
import cc.loach.homekit.app.homekit.translators.HapLightTranslator;
import cc.loach.homekit.app.homekit.settings.HapSettingsImpl;
import cc.loach.homekit.hap.framewok.HapSettings;
import cc.loach.homekit.hap.typedef.accessory.HapAccessory;
import io.vertx.core.Vertx;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    private ImageView imageViewLight1;
    private ImageView imageViewLight2;
    private TextView textViewSetupCode;
    private HomeKit homekit;
    private HapSettings settings;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageViewLight1 = findViewById(R.id.imageViewLight1);
        imageViewLight2 = findViewById(R.id.imageViewLight2);
        textViewSetupCode = findViewById(R.id.textViewSetupCode);

        List<HapAccessory> devices = getDevices();
        settings = new HapSettingsImpl(this);
        homekit = new HomeKit(Vertx.vertx(), settings, devices);
    }

    // 演示版本最多支持2个设备，正式版支持255个设备。
    private List<HapAccessory> getDevices() {
        List<HapAccessory> list =  new ArrayList<>();
        list.add(new HapLightTranslator("aaa", this, imageViewLight1));
        list.add(new HapLightTranslator("bbb", this, imageViewLight2));
        return list;
    }

    public void onButtonStart(View view) {
        // 启动HomeKit服务
        homekit.start()
                .onSuccess(x -> {
                    Log.i(TAG, "start onSuccess");

                    // 显示SetupCode
                    runOnUiThread(() -> textViewSetupCode.setText("已启动, SetupCode: " + settings.setupCode()));
                })
                .onFailure(e -> {
                    Log.d(TAG, "start onFailure: " + e.getMessage());
                });
    }

    public void onButtonStop(View view) {
        // 清空SetupCode
        textViewSetupCode.setText("");

        // 停止HomeKit服务
        homekit.stop()
                .onSuccess(x -> {
                    Log.i(TAG, "stop onSuccess");
                })
                .onFailure(e -> {
                    Log.d(TAG, "stop onFailure: " + e.getMessage());
                });
    }
}